#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8

import sys, os, getopt, re
import codecs
#from pysqlite2 import dbapi2 as sqlite
import sqlite3
from index_gen import *
import subprocess

DEFAULT_INDEX_NAME = 'nameindex.html'
TRADITIONAL_INDEX_NAME = 'nameindex_t.html'

def single_head(fout):
    head = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="file_res/pagestyle.css" media="screen"/>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="Draconic" name="author"/>
<meta content="龍類百科" name="description"/>
<script type="text/javascript">var IMGFOLDERPATH = 'file_res/img_res/dialog_elm/';//图片路径配置</script>
<script type="text/javascript" src="file_res/Dialog.js"></script>

<title>龍類百科（詳盡版）</title>
<script type="text/javascript">
<!--
 iepngfix = function( bgimg ) {
      return 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + bgimg + '", sizingMethod="scale")';
 }
window.onload = function(){
 var isIE=(document.all)?true:false;
 var pagetop = document.getElementById("pagetop");
 var pagecontent = document.getElementById("pagecontent");
 var pagebottom = document.getElementById("pagebottom");
 pagetop.style.backgroundImage = "url(file_res/img_res/pagetop.png)"
 if(isIE) {
  pagetop.style.filter = iepngfix("file_res/img_res/pagetop.png");
  pagetop.style.backgroundImage = "none";
 }
 pagecontent.style.backgroundImage = "url(file_res/img_res/pagecontent.png)"
 if(isIE) {
  pagecontent.style.filter = iepngfix("file_res/img_res/pagecontent.png");
  pagecontent.style.backgroundImage = "none";
 }
 pagebottom.style.backgroundImage = "url(file_res/img_res/pagebottom.png)"
 if(isIE) {
  pagebottom.style.filter = iepngfix("file_res/img_res/pagebottom.png");
  pagebottom.style.backgroundImage = "none";
 }
}
-->
</script>
<script type="text/javascript">
function OpenComment(CommentTitle){
	var diag = new Dialog("Diag1");
	diag.Width = 800;
	diag.Height = 400;
	diag.Title = "提交詞條修改意見";
	diag.URL = "http://yinglong.org/forum/post.php?fid=6";
	diag.ShowMessageRow = true;
	diag.MessageTitle = "【糾錯/反饋】——"+CommentTitle+"";
	diag.Message = "在这裏您可以对这个詞條内容不準確或有誤的地方作一些说明並提出修正意見";

	diag.show();
}
</script>

</head>

<body>
<div id="maincontainer">
  <div id="maintitle"><i>Dracopedia&nbsp;</i></div>
  <div id="pagecontainer">
    <div id="pagetop">&nbsp;</div>
    <div id="pagecontent">
      <div class="page">
         <div class="navbar">

         &nbsp;&nbsp;&nbsp;<a href="http://yinglong.org/" title="去Draconian Zone首頁">Draconian Zone首頁</a>&nbsp;&gt;&gt;&nbsp;<a href="../dracopedia.html">龍族百科</a>&nbsp;&gt;&gt;&nbsp;詳盡版全部內容
         </div>
         <div class="toolbar">
           <p id="calendar" class="left">&nbsp;
            <script type="text/javascript">
            var day="";
            var month="";
            var ampm="";
            var ampmhour="";
            var myweekday="";
            var year="";
            mydate=new Date();
            myweekday=mydate.getDay();
            mymonth=mydate.getMonth()+1;
            myday= mydate.getDate();
            myyear= mydate.getYear();
            year=(myyear > 200) ? myyear : 1900 + myyear;
            if(myweekday == 0)
            weekday=" 星期日 ";
            else if(myweekday == 1)
            weekday=" 星期一 ";
            else if(myweekday == 2)
            weekday=" 星期二 ";
            else if(myweekday == 3)
            weekday=" 星期三 ";
            else if(myweekday == 4)
            weekday=" 星期四 ";
            else if(myweekday == 5)
            weekday=" 星期五 ";
            else if(myweekday == 6)
            weekday=" 星期六 ";
            document.getElementById("calendar").innerHTML="您所在地的時間是："+year+"年"+mymonth+"月"+myday+"日&nbsp;"+weekday;
            </script> 
           </p>
           <p class="right">
     <a href="http://yinglong.org/forum/register.php" title="點此加入Draconian Zone社區，在這裏安家落戶">加入社區</a>&nbsp;|&nbsp;<a href="http://yinglong.org/forum/login.php" title="點此登入Draconian Zone社區，參加交流與討論">登錄社區</a>&nbsp;|&nbsp;<a href="http://yinglong.org/forum/extern.php?action=active&amp;type=RSS" title="本站一有更新，第一時間讓您知道"><img border="0" src="file_res/img_res/rss.gif" alt="RSS"/>&nbsp;訂閱RSS</a>&nbsp;                            
           </p>

         </div>
         <div class="contents">
           <div id="mBody">
           <div class="h1">
             <h1 style="margin: 0px; font-size: 36px;"><b>&nbsp;&nbsp;&nbsp;&nbsp;<img src="file_res/img_res/pedia_logo.gif" alt="logo"/>龍族百科（詳盡版）</b></h1>
             <br/>

             <p style="color: red;">源於網絡，回報網絡。本百科內容大部分來源於互聯網，遵從<a href="http://zh.wikipedia.org/wiki/GFDL" title="查看對GNU自由文檔協議的解釋">GNU自由文檔協議</a>，歡迎自由使用。
             </p>

    """
    fout.write(head)

def num_to_hanz(number):
    hanz_list = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九')
    hanz_str = ''
    if (int(number/10) > 0):
        hanz_str += hanz_list[int(number/10)] + u'十'
    hanz_str += hanz_list[int(number%10)]
    return hanz_str

def generate_index(dbcur, htmlprefix, prepage, traditional):
    f_out = codecs.open(htmlprefix+'0.html', 'w', 'utf8')
    fout = f_out
    if not traditional:
        fout = STConvert(f_out)

    single_head(fout)
    fout.write(u"""
<div class="h2">
<h2>索引</h2>
<div class="list">
    """)

    dbcur.execute('select count(*) from pedia')
    count = dbcur.fetchone()[0]
    dbcur.execute('select id, title, accuracy from pedia order by accuracy desc, id')
    i = 0
    for row in dbcur:
        if row['accuracy'] == 0:
            li = u'<p><a class="transnone" href="%s%d.html#%s" title="見第%s頁"><img src="file_res/img_res/item_ico.gif" alt="." border="0"/>%s</a></p>\n' % (htmlprefix, (int(i/prepage)+1), row['id'], num_to_hanz(int(i/prepage)+2), row['title'])
        elif row['accuracy'] == 1:
            li = u'<p><a class="translow" href="%s%d.html#%s" title="見第%s頁"><img src="file_res/img_res/item_ico.gif" alt="." border="0"/>%s</a></p>\n' % (htmlprefix, (int(i/prepage)+1), row['id'], num_to_hanz(int(i/prepage)+2), row['title'])
        elif row['accuracy'] == 2:
            li = u'<p><a class="transhigh" href="%s%d.html#%s" title="見第%s頁"><img src="file_res/img_res/item_ico.gif" alt="." border="0"/>%s</a></p>\n' % (htmlprefix, (int(i/prepage)+1), row['id'], num_to_hanz(int(i/prepage)+2), row['title'])
        fout.write(li)
        i = i+1

    fout.write(u"""
</div>
</div>
    """)
    #feedback_window(fout)
    public_tail(fout, 1, htmlprefix, int(count/prepage)+2, 0)
    f_out.close()

def generate_body(dbcur, htmlprefix, prepage, traditional):
    dbcur.execute('select count(*) from pedia')
    count = dbcur.fetchone()[0]

    offset = 0
    while offset < count:
        page = offset / prepage + 1
        f_out = codecs.open(htmlprefix+'%d.html'%(page), 'w', 'utf8')
        fout = f_out
        if not traditional:
            fout = STConvert(f_out)

        single_head(fout)
        fout.write(u"""
<div class="h2">
<h2>正文</h2>
        """)
        dbcur.execute('select * from pedia order by accuracy desc, id limit %d offset %d' % (prepage, offset))
        for row in dbcur:
            public_body(fout, row, 'file_res/img_doc/')

        fout.write(u"""
</div>
        """)
        #feedback_window(fout)
        public_tail(fout, 1, htmlprefix, int(count/prepage)+2, page)
        f_out.close()
        offset += prepage

class STConvert():
    def __init__(self, out):
        self.out = out

    def write(self, string):
        p1 = subprocess.Popen(["echo", string], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(["cconv", "-f", "UTF8", "-t", "UTF8-CN"], stdin=p1.stdout, stdout=subprocess.PIPE)
        output = unicode(p2.communicate()[0], "utf-8")
        self.out.write(output)

def generator(dbfile, htmlprefix, traditional=False):
    print 'input db file:', dbfile
    con = sqlite3.connect(dbfile)
    con.row_factory = sqlite3.Row
    cur = con.cursor()

    generate_index(cur, htmlprefix, 10, traditional)
    generate_body(cur, htmlprefix, 10, traditional)

    cur.close()

def usage():
    print("""
    example: xxx.py -i xx.db -o xx.html

    -h   print this message
    -i   input database name
    -o   output html name
    """)

def main(argv):
    global DEFAULT_INDEX_NAME
    DEFAULT_PRIFIX = 'dracondict_'
    TRADITIONAL_PRIFIX = 'dracondict_t_'
    file_db = 'dpedia.db.sqlite'
    file_html = DEFAULT_PRIFIX
    traditional = False
    try:
        opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output=', 'traditional']) 
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-i', '--input'):
            file_db = arg
        elif opt in ('-o', '--output'):
            file_html = arg
        elif opt in ('-t', '--traditional'):
            traditional = True
            file_html = TRADITIONAL_PRIFIX
    if traditional:
        DEFAULT_INDEX_NAME = TRADITIONAL_INDEX_NAME
    generator(file_db, file_html, traditional)

if __name__ == '__main__':
    main(sys.argv[1:])

